package test.closure

import groovy.transform.CompileStatic

//定义一个Closure类型的闭包
def listener = { e -> println "Clicked on $e.source" }
assert listener instanceof Closure
//定义直接指定为Closure类型的闭包
Closure callback = { println 'Done!' }
Closure<Boolean> isTextFile = { File it ->
    it.name.endsWith('.txt')
}


def code = { 123 }
assert code() == 123
assert code.call() == 123

def isOdd = { int i -> i % 2 == 1 }
assert isOdd(3) == true
assert isOdd.call(2) == false

//特别注意，如果闭包没定义参数则默认隐含一个名为it的参数，如下例子：

def isEven = { it % 2 == 0 }
assert isEven(3) == false
assert isEven.call(2) == true

// closure 递归 (1)
def fib // 需要先声明一下，奇葩呀
fib = { n ->
    if (n <= 0) return 0
    if (n == 1) return 1
    return fib(n - 2) + fib(n - 1)
}
println(fib(6))

// closure 递归 (2)
def fib2 = { n ->
    if (n <= 0) return 0
    if (n == 1) return 1
    return call(n - 2) + call(n - 1) // closure内call调用自己
}
println(fib2(6))

// closure 递归 (3)
@CompileStatic
class ClosureRecursiveFab {
    static void main(String[] args) {
        Closure<Integer> fib // 在@CompileStatic要求下，用Closure类来声明
        fib = { int n ->
            if (n <= 0) return 0
            if (n == 1) return 1
            return fib(n - 2) + fib(n - 1)
        }
        println(fib(6))
        println(mFib(7))
    }

    /**
     * 当然也可以老老实实定义为method了
     */
    static int mFib(int n) {
        if (n <= 0) return 0
        if (n == 1) return 1
        return mFib(n - 2) + mFib(n - 1)
    }
}
ClosureRecursiveFab.main()
